import logging
from logging.handlers import TimedRotatingFileHandler, RotatingFileHandler
from datetime import datetime
import time

global_logger = logging.getLogger("test")
global_logger.setLevel(logging.DEBUG)

formatter = logging.Formatter("%(asctime)s  %(levelname)s: %(message)s")

null_handler = logging.NullHandler()
global_logger.addHandler(null_handler)


def add_stream_handler(global_logger):
    streamHandler = logging.StreamHandler()
    streamHandler.setLevel(logging.INFO)
    streamHandler.setFormatter(formatter)
    global_logger.addHandler(streamHandler)


def add_file_handler(global_logger):
    file_handler = logging.FileHandler("e:\\test_log.log", mode="a", encoding="utf8")
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    global_logger.addHandler(file_handler)


def add_time_rotating_file_handler(global_logger):
    file_handler = TimedRotatingFileHandler("e:\\log", "S", 5)
    file_handler.suffix = "%Y%m%d.log"
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    global_logger.addHandler(file_handler)


def add_file_rotating_file_handler(global_logger):
    file_handler = RotatingFileHandler("test_log.log", maxBytes=1024, backupCount=10, encoding="utf8")
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    global_logger.addHandler(file_handler)


if __name__ == '__main__':
    add_stream_handler(global_logger)
    add_file_handler(global_logger)
    while True:
        try:
            #global_logger.info("hello info")
            #global_logger.debug("hello debug")
            global_logger.log(logging.INFO, "hello info")
            global_logger.log(logging.DEBUG, "hello debug")
        except:
            print('error')
        time.sleep(1)
